<?php

namespace App\Service;

use App\Library\ChargeCache;

class StationService
{
    use ChargeCache;

    /**
     * 查询电站信息
     * @param $params
     * @return mixed
     */
    public function queryStationsInfo($params)
    {
        if ($params['PageNo'] > 2) {
            return ['ItemSize' => 1, 'PageNo' => 1, 'PageCount' => 0, 'StationInfos' => []];
        }
        return $this->getStation();
    }

    /**
     * 设备接口状态查询
     * @param $params
     * @return mixed
     */
    public function queryStationStatus($params)
    {
        $res = array_values($params['StationIDs']);
        $station = $this->getStation();
        $stations = collect($station['StationInfos'])->keyBy('StationID')->toArray();
        $data = [];
        foreach ($res as $re) {
            if (!empty($stations[$re])) {
                $data['StationStatusInfos'][] = [
                    'StationID' => $re,
                    'ConnectorStatusInfos' => static::handle($stations[$re]['EquipmentInfos'] ?? []),
                ];
            }
        }
        return $data;
    }

    /**
     * 处理数据
     * @param $equipmentInfo
     * @return array
     */
    public static function handle($equipmentInfo)
    {
        if (empty($equipmentInfo)){
            return [];
        }
        $cache = (new ChargeService());
        $res = [];
        foreach ($equipmentInfo as $item1) {
            foreach ($item1['ConnectorInfos'] as $item) {
                $getCache = $cache->getChargeStatusCache($item['ConnectorID']);
                $status = 1;
                if (!empty($getCache) && json_decode($getCache,true)['status'] == 2){
                    $status = 3;
                }
                $res[] = ['ConnectorID' => $item['ConnectorID'], 'Status' =>$status, 'ParkStatus' => 0, 'LockStatus' => 0];
            }
        }
        return $res;
    }

    /**
     * 查询业务策略信息
     * @param $params
     * @return array
     */
    public function queryEquipBusinessPolicy($params)
    {
        $data = [];
        $data['PolicyInfos'] = [
            [
                'StartTime' => '000000',
                'ElecPrice' => '0.72',
                'SevicePrice' => '0.20'
            ],
            [
                'StartTime' => '240000',
                'ElecPrice' => '0.72',
                'SevicePrice' => '0.20'
            ]
        ];
        return $data;
    }

    /**
     * 查询电站信息
     * @return array|mixed
     */
    public function getStation()
    {
        $local = public_path('/') . 'station.json';
        $data = file_get_contents($local);
        if (empty($data)) {
            return [];
        }
        return json_decode($data, true);
    }
}
